liwe.fx.fade = {};

liwe.fx.fade._do_fade_in = function ( e )
{
	e.fade_val = liwe.fx.set_opacity ( e, e.fade_val + e.fade_amount );
	
	if ( e.fade_val < 100 ) setTimeout ( function () { liwe.fx.fade._do_fade_in ( e ); }, e.fade_millis );
	else if ( e.fade_cback ) e.fade_cback ( e );
};

liwe.fx.fade._do_fade_out = function ( e )
{
	e.fade_val = liwe.fx.set_opacity ( e, e.fade_val - e.fade_amount );

	if ( e.fade_val > 0 ) setTimeout ( function () { liwe.fx.fade._do_fade_out ( e ); }, e.fade_millis );
	else if ( e.fade_cback ) e.fade_cback ( e );
};

/* =======================================================================
	PUBLIC FUNCTIONS
======================================================================= */
liwe.fx.fade_in = function ( el, amount, millis, cback )
{
	el.fade_cback = cback;

	if ( ! amount ) amount = 10;
	if ( ! millis ) millis = 100;

	el.fade_amount = amount;
	el.fade_millis = millis;

	el.fade_val = liwe.fx.set_opacity ( el, 0 );
	// el.style.visibility = 'inherit';

	liwe.fx.fade._do_fade_in ( el );
};

liwe.fx.fade_out = function ( el, amount, millis, cback )
{
	el.fade_cback = cback;

	if ( ! amount ) amount = 10;
	if ( ! millis ) millis = 100;

	el.fade_amount = amount;
	el.fade_millis = millis;

	el.fade_val = liwe.fx.set_opacity ( el, 100 );
	el.style.visibility = 'inherit';

	liwe.fx.fade._do_fade_out ( el );
};

/* ==================
   WEBKIT & MOZILLA
===================*/
liwe.fx.fade_default_timing = 'ease-in';

liwe.fx.fade_in = function ( el, cback, millis, timing )
{
	liwe.fx.fade ( el, 'in', cback, millis, timing );
};

liwe.fx.fade_out = function ( el, cback, millis, timing )
{
	liwe.fx.fade ( el, 'out', cback, millis, timing );
};

liwe.fx.fade = function ( el, dir, cback, millis, timing )
{
	if ( ! el || el.dataset [ 'animating' ] ) return;
	
	if ( ( dir == 'in' && el.style.opacity == '1' ) || ( dir == 'out' && el.style.opacity == '0') ) return;
	
	if ( ! millis ) millis = liwe.fx.fade_default_millis;
	if ( ! timing ) timing = liwe.fx.fade_default_timing;

	var evthandler = function ( event ) 
	{
		this.removeEventListener ( 'webkitTransitionEnd', evthandler );
		this.removeEventListener ( 'transitionend', evthandler );

		this.style.WebkitTransition = '';
		this.style.MozTransition = '';
		this.dataset [ 'animating' ] = false;

		if ( cback ) cback ();
	};
	
	el._animating = true;
	
	el.addEventListener ( 'webkitTransitionEnd', evthandler );
	el.addEventListener ( 'transitionend', evthandler );
	
	var transition = 'opacity ' + millis + 'ms ' + timing;
	el.style.WebkitTransition = transition;
	el.style.MozTransition = transition; 
	
	el.style.opacity = ( dir == 'in' ? '1' : '0' );
};
